//
//  AdvertisingPageViewController.swift
//  iModern
//
//  Created by Ralf on 8/12/15.
//  Copyright (c) 2015 com.starlooking. All rights reserved.
//

import UIKit

class AdvertisingPageViewController: ViewController, UITableViewDelegate, UITableViewDataSource, UMSocialUIDelegate, UIActionSheetDelegate
{
    var tableView:         UITableView!
    var commentTextField:  UITextField!
    var submitButton:      UIButton!
    let appDelegate     = UIApplication.sharedApplication().delegate as! AppDelegate
    let screen          = UIScreen.mainScreen().bounds
    var activity:          NSMutableDictionary!
    var pageViewImageCell: PageViewImageCell!
    var relatedProducts = NSMutableArray()
    var lastReview:       NSDictionary?
    //    var array = NSMutableArray()
    var bottomConstraint:  NSLayoutConstraint!
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor(white: 0.98, alpha: 1)
        
        let frame = CGRect(x: 0, y: 0, width: screen.width, height: screen.height - 105)
        tableView = UITableView(frame: frame)
        view.addSubview(tableView)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = UIColor.whiteColor()
        tableView.separatorStyle = .None
        
        initCommentTextField()
        initSubmitButton()
        
        self.tableView.registerNib(UINib(nibName: "ArticlePageViewAvatarCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "AVATAR")
        self.tableView.registerNib(UINib(nibName: "PageViewImageCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "IMAGE")
        self.tableView.registerNib(UINib(nibName: "PageViewMessageCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "MESSAGE")
        self.tableView.registerNib(UINib(nibName: "PageViewLinkCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "LINK")
        self.tableView.registerNib(UINib(nibName: "AdvertisingPageViewBuy", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "BUY")
        
        self.tableView.registerNib(UINib(nibName: "PageViewSummaryCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "SUMMARY")
        self.tableView.registerNib(UINib(nibName: "AdvertisingPageViewCommentCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "COMMENT")
        
        self.tableView.registerNib(UINib(nibName: "AdvertisingPageViewDescriptionCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "DESCRIPTION")
        self.tableView.registerNib(UINib(nibName: "AdvertisingPageViewAttachmentCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "ATTACHMENT")
        self.tableView.registerNib(UINib(nibName: "AdvertisingPageViewAttachmentDescCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "ATTACHMENTDESC")
        self.tableView.registerNib(UINib(nibName: "AdvertisingPageViewManufacturingCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "MANUFACTURING")
        
        initBackButton()
        initReportButton()
        
        loadLastReview()
    }
    
    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(animated: Bool)
    {
        super.viewWillAppear(animated);
        
        MobClick.beginLogPageView("AdvertisingPageView")
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillShowNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillHideNotification, object: nil)
        
        //        NSNotificationCenter.defaultCenter().addObserver(self, selector: "tableViewScrollToBottom", name: UIKeyboardDidShowNotification, object: nil)
    }
    
    override func viewWillDisappear(animated: Bool)
    {
        super.viewWillDisappear(animated);
        MobClick.endLogPageView("AdvertisingPageView")
    }
    
    func initReportButton()
    {
        //        let image        = UIImage(named: "Share-Small.png")!.imageWithRenderingMode(.AlwaysOriginal)
        //        let button       = UIBarButtonItem(image: image, style: .Plain, target: self, action: "showMenu:")
        //        let submitImage  = UIImage(named: "Report-60")!.imageWithRenderingMode(.AlwaysOriginal)
        //        let submitButton = UIBarButtonItem(image: submitImage, style: .Plain, target: self, action: "reportMenu:")
        //        var arrays       = [button, submitButton]
        //        self.navigationItem.rightBarButtonItems = arrays
        
        
        let image1  = UIImage(named: "Share-Small.png")
        let button1 = UIButton()
        button1.frame = CGRectMake(0, 0, 30, 30)
        button1.setImage(image1, forState: .Normal)
        button1.addTarget(self, action: Selector("loadShareMenu:"), forControlEvents: UIControlEvents.TouchUpInside)
        let showButton = UIBarButtonItem(customView: button1)
        self.navigationItem.rightBarButtonItem = showButton
    }
    
    @IBAction func loadShareMenu(sender: AnyObject)
    {
        let alertContorller = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
        let alertCancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
        let alertA = UIAlertAction(title: "分享", style: UIAlertActionStyle.Default) {
            (action: UIAlertAction!) -> Void in
            self.showMenu()
        }
        let alertB = UIAlertAction(title: "举报", style: UIAlertActionStyle.Default) {
            (action: UIAlertAction!) -> Void in
            self.reportMenu()
        }
        alertContorller.addAction(alertCancel)
        alertContorller.addAction(alertA)
        alertContorller.addAction(alertB)
        self.presentViewController(alertContorller, animated: true, completion: nil)
    }
    
    
    // MARK: - Table view data source
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        let article     = activity["article"] as! NSDictionary
        let attachments = article["attachments"] as? NSArray
        if lastReview != nil
        {
            return 11 + attachments!.count*2
        }
        else
        {
            return 10 + attachments!.count*2
        }
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        let article = activity["article"] as! NSDictionary
        let attachments = article["attachments"] as! NSArray
        
        if lastReview != nil
        {
            switch indexPath.row
            {
            case 0: //avatar
                return screen.size.width
            case 1: //image
                return 45
            case 2:
                let message = article["message"] as! NSString
                let size    = sizeOfText(message)
                return size.height
            case 3:
                return 40.0 /// link
            case 4: // message
                return 40.0 // buy
            case 5:
                return 190.0 // avatar
            case 6:
                return 160 // last comment
            case 7:
                return 40.0
            case 8:
                let pmi = article["pmi"] as? NSString
                if pmi != nil
                {
                    let size = sizeOfText(pmi!)
                    return size.height * 1.2 + 10
                }
                else
                {
                    return 40 + 40
                }
            case 9:
                let pom = article["pom"] as? NSString
                if pom != nil
                {
                    let size = sizeOfText(pom!)
                    return size.height * 1.2 + 15
                }
                else
                {
                    return 40
                }
            case 10:
                let story = article["story"] as? NSString
                if story != nil
                {
                    let size = sizeOfText(story!)
                    return size.height * 1.2 + 15
                }
                else
                {
                    return 40
                }
            default: // related service
                let attachmentobj = attachments[(indexPath.row-12)/2] as! NSMutableDictionary
                if (indexPath.row-12)%2 == 0{
                    return UIScreen.mainScreen().bounds.size.width
                }
                else{
                    let message = attachmentobj["description"] as! NSString
                    let size    = sizeOfText(message)
                    return size.height
                }
            }
        }
        else
        {
            switch indexPath.row
            {
            case 0: //avatar
                return screen.size.width
            case 1: //image
                return 45
            case 2:
                let article = activity["article"] as! NSDictionary
                let message = article["message"] as! NSString
                let size    = sizeOfText(message)
                return size.height
            case 3:
                return 40.0 /// link
            case 4: // message
                return 40.0 // buy
            case 5:
                return 190.0 // avatar
            case 6: // message
                return 40.0
            case 7:
                let pmi = article["pmi"] as? NSString
                if pmi != nil
                {
                    let size = sizeOfText(pmi!)
                    return size.height * 1.2 + 10
                }
                else
                {
                    return 40 + 40
                }
            case 8:
                let pom = article["pom"] as? NSString
                if pom != nil
                {
                    let size = sizeOfText(pom!)
                    return size.height * 1.2 + 15
                }
                else
                {
                    return 40
                }
            case 9:
                let story = article["story"] as? NSString
                if story != nil
                {
                    let size = sizeOfText(story!)
                    return size.height * 1.2 + 15
                }
                else
                {
                    return 40
                }
            default: // related service
                let attachmentobj = attachments[(indexPath.row-10)/2] as! NSMutableDictionary
                if (indexPath.row-10)%2 == 0{
                    return UIScreen.mainScreen().bounds.size.width
                }
                else{
                    let message = attachmentobj["description"] as! NSString
                    let size    = sizeOfText(message)
                    return size.height
                }
            }
        }
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let article     = activity["article"] as! NSDictionary
        let attachments = article["attachments"] as! NSArray
        
        if lastReview != nil
        {
            switch indexPath.row
            {
            case 0:
                _ = activity["article"] as! NSDictionary
                pageViewImageCell = tableView.dequeueReusableCellWithIdentifier("IMAGE", forIndexPath: indexPath) as! PageViewImageCell
                pageViewImageCell.setData(activity)
                return pageViewImageCell
            case 1:
                _ = activity["article"] as! NSDictionary
                let cell    = tableView.dequeueReusableCellWithIdentifier("SUMMARY", forIndexPath: indexPath) as! PageViewSummaryCell
                cell.setData(activity)
                return cell
            case 2:
                let cell = tableView.dequeueReusableCellWithIdentifier("MESSAGE", forIndexPath: indexPath) as! PageViewMessageCell
                cell.setData(activity)
                return cell
            case 3:
                let cell = tableView.dequeueReusableCellWithIdentifier("LINK", forIndexPath: indexPath) as! PageViewLinkCell
                cell.setData(activity)
                return cell
            case 4:
                let cell = tableView.dequeueReusableCellWithIdentifier("BUY", forIndexPath: indexPath) as! AdvertisingPageViewBuy
                cell.setData(activity)
                return cell
            case 5:
                let cell = tableView.dequeueReusableCellWithIdentifier("AVATAR", forIndexPath: indexPath) as! ArticlePageViewAvatarCell
                cell.setData(activity)
                return cell
            case 6:
                let cell = tableView.dequeueReusableCellWithIdentifier("COMMENT", forIndexPath: indexPath) as! AdvertisingPageViewCommentCell
                let article = activity["article"] as! NSDictionary
                
                
                //                cell.setData(lastReview!)
                cell.setData(lastReview!, advertisingID: article["id"] as! Int)
                return cell
            case 7:
                let cell = tableView.dequeueReusableCellWithIdentifier("MANUFACTURING", forIndexPath: indexPath) as! AdvertisingPageViewManufacturingCell
                //var pmi  = article["pmi"] as? String
                cell.selectionStyle = UITableViewCellSelectionStyle.None
                //                cell.setData("制作流程", description: pmi)
                return cell
            case 8:
                let cell = tableView.dequeueReusableCellWithIdentifier("DESCRIPTION", forIndexPath: indexPath) as! AdvertisingPageViewDescriptionCell
                let pmi  = article["pmi"] as? String
                cell.selectionStyle = UITableViewCellSelectionStyle.None
                cell.setData("制作流程", description: pmi)
                return cell
            case 9:
                let cell = tableView.dequeueReusableCellWithIdentifier("DESCRIPTION", forIndexPath: indexPath) as! AdvertisingPageViewDescriptionCell
                let pom  = article["pom"] as? String
                cell.setData("原料配方", description: pom)
                return cell
            case 10:
                let cell  = tableView.dequeueReusableCellWithIdentifier("DESCRIPTION", forIndexPath: indexPath) as! AdvertisingPageViewDescriptionCell
                let story = article["story"] as? String
                cell.setData("特色说明", description: story)
                return cell
            default:
                let attachmentobj = attachments[(indexPath.row-11)/2] as! NSMutableDictionary
                if (indexPath.row-11)%2 == 0{
                    let cell       = tableView.dequeueReusableCellWithIdentifier("ATTACHMENT", forIndexPath: indexPath) as! AdvertisingPageViewAttachmentCell
                    cell.setData(attachmentobj)
                    return cell
                }
                else{
                    let desc = attachmentobj["description"] as! NSString
                    let cell = tableView.dequeueReusableCellWithIdentifier("ATTACHMENTDESC", forIndexPath: indexPath) as! AdvertisingPageViewAttachmentDescCell
                    cell.setData(desc as String)
                    return cell
                }
            }
        }
        else
        {
            switch indexPath.row
            {
            case 0:
                //let article = activity["article"] as! NSDictionary
                pageViewImageCell = tableView.dequeueReusableCellWithIdentifier("IMAGE", forIndexPath: indexPath) as! PageViewImageCell
                pageViewImageCell.setData(activity)
                return pageViewImageCell
            case 1:
                //let article = activity["article"] as! NSDictionary
                let cell    = tableView.dequeueReusableCellWithIdentifier("SUMMARY", forIndexPath: indexPath) as! PageViewSummaryCell
                cell.setData(activity)
                return cell
            case 2:
                let cell = tableView.dequeueReusableCellWithIdentifier("MESSAGE", forIndexPath: indexPath) as! PageViewMessageCell
                cell.setData(activity)
                return cell
            case 3:
                let cell = tableView.dequeueReusableCellWithIdentifier("LINK", forIndexPath: indexPath) as! PageViewLinkCell
                cell.setData(activity)
                return cell
            case 4:
                let cell = tableView.dequeueReusableCellWithIdentifier("BUY", forIndexPath: indexPath) as! AdvertisingPageViewBuy
                cell.setData(activity)
                return cell
            case 5:
                let cell = tableView.dequeueReusableCellWithIdentifier("AVATAR", forIndexPath: indexPath) as! ArticlePageViewAvatarCell
                cell.setData(activity)
                return cell
            case 6:
                let cell = tableView.dequeueReusableCellWithIdentifier("MANUFACTURING", forIndexPath: indexPath) as! AdvertisingPageViewManufacturingCell
                //                var pmi  = article["pmi"] as? String
                cell.selectionStyle = UITableViewCellSelectionStyle.None
                //                cell.setData("制作流程", description: pmi)
                return cell
            case 7:
                let cell = tableView.dequeueReusableCellWithIdentifier("DESCRIPTION", forIndexPath: indexPath) as! AdvertisingPageViewDescriptionCell
                let pmi  = article["pmi"] as? String
                cell.selectionStyle = UITableViewCellSelectionStyle.None
                cell.setData("制作流程", description: pmi)
                return cell
            case 8:
                let cell = tableView.dequeueReusableCellWithIdentifier("DESCRIPTION", forIndexPath: indexPath) as! AdvertisingPageViewDescriptionCell
                let pom  = article["pom"] as? String
                cell.setData("原料配方", description: pom)
                return cell
            case 9:
                let cell  = tableView.dequeueReusableCellWithIdentifier("DESCRIPTION", forIndexPath: indexPath) as! AdvertisingPageViewDescriptionCell
                let story = article["story"] as? String
                cell.setData("特色说明", description: story)
                return cell
            default:
                let attachmentobj = attachments[(indexPath.row-10)/2] as! NSMutableDictionary
                if (indexPath.row-10)%2 == 0{
                    let cell       = tableView.dequeueReusableCellWithIdentifier("ATTACHMENT", forIndexPath: indexPath) as! AdvertisingPageViewAttachmentCell
                    cell.setData(attachmentobj)
                    return cell
                }
                else{
                    let desc = attachmentobj["description"] as! NSString
                    let cell = tableView.dequeueReusableCellWithIdentifier("ATTACHMENTDESC", forIndexPath: indexPath) as! AdvertisingPageViewAttachmentDescCell
                    cell.setData(desc as String)
                    return cell
                }
            }
        }
    }
    
    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return NO if you do not want the specified item to be editable.
    return true
    }
    */
    
    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
    // Delete the row from the data source
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    } else if editingStyle == .Insert {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
    }
    */
    
    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
    
    }
    */
    
    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return NO if you do not want the item to be re-orderable.
    return true
    }
    */
    
    /*
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    }
    */
    
    func keyboardChange(notification: NSNotification)
    {
        let userInfo:          NSDictionary   = notification.userInfo!
        let animationDuration: NSTimeInterval = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        
        //    var animationCurve : UIViewAnimationCurve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! UIViewAnimationCurve
        
        let keyboardEndFrame: CGRect = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        UIView.beginAnimations(nil, context: nil)
        UIView.setAnimationDuration(animationDuration)
        //    UIView.setAnimationCurve(animationCurve)
        
        //    if notification.name == UIKeyboardWillShowNotification {
        //        self.bottomConstraint.constant = keyboardEndFrame.size.height + 40
        //    }
        //    else {
        //        self.bottomConstraint.constant = 40
        //    }
        
        view.layoutIfNeeded()
        
        var newFrame = self.commentTextField.frame
        
        newFrame.origin.y = keyboardEndFrame.origin.y - 64 - newFrame.size.height
        
        self.commentTextField.frame = newFrame
        
        var submitFrame = self.submitButton.frame
        submitFrame.origin.y = keyboardEndFrame.origin.y - 64 - submitFrame.size.height
        self.submitButton.frame = submitFrame
        UIView.commitAnimations()
    }
    
    deinit
    {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
        // 2.删除键盘隐藏时的观察者
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
    {
        self.view.endEditing(true)
    }
    //    func tableViewScrollToBottom {
    //
    //    let indexPath = [NSIndexPath indexPathForRow:messages.count - 1 inSection:0];
    //    [self.ChatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    //    }
    func scrollViewWillBeginDragging(scrollView: UIScrollView)
    {
        self.view.endEditing(true)
    }
    
    func sizeOfText(text: NSString) -> CGSize
    {
        let paragraphStyle = NSMutableParagraphStyle()
        
        paragraphStyle.lineHeightMultiple = 16
        paragraphStyle.maximumLineHeight = 20
        paragraphStyle.minimumLineHeight = 20
        
        //        paragraphStyle.firstLineHeadIndent = 20
        paragraphStyle.alignment = .Left
        
        let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(14),
            NSParagraphStyleAttributeName: paragraphStyle,
            NSForegroundColorAttributeName: UIColor.darkGrayColor()]
        
        let frame = CGSizeMake(screen.size.width, screen.size.height)
        let options = unsafeBitCast(NSStringDrawingOptions.TruncatesLastVisibleLine.rawValue|NSStringDrawingOptions.UsesLineFragmentOrigin.rawValue |
            NSStringDrawingOptions.UsesFontLeading.rawValue,
            NSStringDrawingOptions.self)
        let size  = text.boundingRectWithSize(frame, options: options, attributes: attributes, context: nil)
        return size.size
    }
    
    @IBAction func makeAppointment(sender: AnyObject)
    {
        if appDelegate.isLogged()
        {
            let controller = MakeAppointmentViewController(data: activity as [NSObject:AnyObject])
            controller.setData(activity as [NSObject:AnyObject])
            self.pushViewController(controller)
        }
        else
        {
            login()
        }
    }
    
    func showMenu()
    {
        let text            = activity.objectForKey("article")?.objectForKey("message") as! String
        let thumbnailURL    = activity.objectForKey("article")?.objectForKey("thumbnailURL") as! String
        let url             = appDelegate.parameterManager.server + "/" + thumbnailURL
        let data            = NSData(contentsOfURL: NSURL(string: url)!)
        let image           = UIImage(data: data!)
        var array: [String] = [UMShareToSina, UMShareToTencent, UMShareToSms]
        
        if TencentOAuth.iphoneQQInstalled()
        {
            array.append(UMShareToQQ)
        }
        
        if (WXApi.isWXAppInstalled())
        {
            array.append(UMShareToWechatFavorite)
            array.append(UMShareToWechatTimeline)
            array.append(UMShareToWechatSession)
        }
        if TencentOAuth.iphoneQZoneInstalled()
        {
            array.append(UMShareToQzone)
        }
        
        UMSocialSnsService.presentSnsIconSheetView(self, appKey: UMSocialData.appKey(), shareText: text as String, shareImage: image, shareToSnsNames: array as [AnyObject], delegate: self)
    }
    
    func reportMenu()
    {
        if appDelegate.isLogged()
        {
            //        let Controller = SubmitReportViewController()
            let Controller = SubmitReportFormViewController()
            let report     = NSMutableDictionary()
            
            report.setValue("Article", forKey: "source")
            report.setValue(activity.objectForKey("article")?.objectForKey("id"), forKey: "sourceID")
            Controller.report = report
            
            self.pushViewController(Controller)
        }
        else
        {
            login()
        }
    }
    
    func loadLastReview()
    {
        let article = activity["article"] as! NSDictionary
        let numberOfReview = article["numberOfReview"] as? Int
        if numberOfReview > 0
        {
            lastReview = article["lastReview"] as? NSDictionary
        }
    }
    
    func initCommentTextField()
    {
        let frame = CGRect(x: 5, y: tableView.frame.origin.y + tableView.frame.size.height + 5, width: screen.width - 120, height: 30)
        commentTextField = UITextField(frame: frame)
        commentTextField.placeholder = "发布评论"
        commentTextField.font = UIFont.systemFontOfSize(12)
        commentTextField.layer.borderColor = UIColor.lightGrayColor().CGColor
        commentTextField.layer.borderWidth = 1.0
        commentTextField.layer.cornerRadius = 4
        commentTextField.layer.masksToBounds = true
        //        commentTextField
        commentTextField.backgroundColor = UIColor.whiteColor()
        view.addSubview(commentTextField)
    }
    
    func initSubmitButton()
    {
        let frame = CGRect(x: commentTextField.frame.origin.x + commentTextField.frame.size.width + 5, y: tableView.frame.origin.y + tableView.frame.size.height + 5, width: screen.width - commentTextField.frame.size.width - 15, height: 30)
        submitButton = UIButton(frame: frame)
        submitButton.titleLabel?.font = UIFont.systemFontOfSize(12)
        submitButton.backgroundColor = Theme.theme_color
        submitButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        //let numberOfComment = activity.objectForKey("article")?.objectForKey("numberOfComment") as! Int
        //        submitButton.setTitle("\(numberOfComment)人评论", forState: .Normal)
        submitButton.setTitle("发布评论", forState: .Normal)
        
        submitButton.layer.cornerRadius = 4
        submitButton.layer.masksToBounds = true
        submitButton.addTarget(self, action: "addComments:", forControlEvents: .TouchUpInside)
        view.addSubview(submitButton)
    }
    
    @IBAction func addComments(sender: AnyObject)
    {
        if appDelegate.isLogged()
        {
            let message = commentTextField.text!
            let filter = SensitiveWordsFilter()
            let valid: Bool = filter.validating(message as String)
            if !valid
            {
                self.alertWarningMessage("你在描述里填写的信息可能包含敏感内容.")
                return
            }
            
            if message.utf8.count > 0
            {
                let commentManager = CommentManager()
                let articleId      = activity.objectForKey("article")!.objectForKey("id") as! Int
                let rs             = commentManager.addComment(String(articleId), comment: message as String)
                
                if rs != nil
                {
                    if !rs!.hasErrors()
                    {
                        commentTextField.text = nil
                        tableView.endEditing(true)
                    }
                    else if rs!.errorCode == 3010
                    {
                        alertUserStatusException()
                    }
                    else
                    {
                        alertErrorMessage(rs!.errorMessage)
                    }
                }
                else
                {
                    alertNetworkConnectionException()
                }
            }
        }
        else
        {
            login()
        }
        self.tableView.reloadData()
    }
}
